package com.hck.app.service;

import com.hck.domain.health.model.entity.*;
import com.hck.domain.health.service.IHealthService;
import com.hck.infrastructure.persistent.dao.*;
import com.hck.infrastructure.persistent.po.*;
import com.hck.infrastructure.persistent.repository.HealthProfileRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 健康管理服务实现类
 */
@Slf4j
@Service
public class HealthService implements IHealthService {

    @Resource
    private HealthProfileRepository healthProfileRepository;
    
    @Resource
    private IHealthCheckRecordDao healthCheckRecordDao;
    
    @Resource
    private IHealthReportDao healthReportDao;
    
    @Resource
    private IHealthAlertDao healthAlertDao;

    // ==================== 健康档案相关 ====================
    
    @Override
    public HealthProfileEntity getHealthProfile(Long userId) {
        return healthProfileRepository.findByUserId(userId);
    }

    @Override
    public void saveHealthProfile(HealthProfileEntity profile) {
        healthProfileRepository.save(profile);
    }

    @Override
    public void updateHealthProfile(HealthProfileEntity profile) {
        healthProfileRepository.save(profile);
    }

    // ==================== 健康检查记录相关 ====================
    
    @Override
    public void addHealthCheckRecord(HealthCheckRecordEntity record) {
        HealthCheckRecord po = new HealthCheckRecord();
        BeanUtils.copyProperties(record, po);
        
        if (record.getCheckDate() == null) {
            po.setCheckDate(new Date());
        }
        po.setCreateTime(new Date());
        po.setUpdateTime(new Date());
        
        healthCheckRecordDao.insert(po);
        record.setId(po.getId());
    }

    @Override
    public List<HealthCheckRecordEntity> getHealthCheckRecords(Long userId, String checkType) {
        List<HealthCheckRecord> pos;
        if (checkType != null && !checkType.trim().isEmpty()) {
            pos = healthCheckRecordDao.selectByUserIdAndType(userId, checkType);
        } else {
            pos = healthCheckRecordDao.selectByUserId(userId);
        }
        
        return pos.stream().map(po -> {
            HealthCheckRecordEntity entity = new HealthCheckRecordEntity();
            BeanUtils.copyProperties(po, entity);
            return entity;
        }).collect(Collectors.toList());
    }

    @Override
    public HealthCheckRecordEntity getLatestHealthCheckRecord(Long userId, String checkType) {
        HealthCheckRecord po = healthCheckRecordDao.selectLatestByUserIdAndType(userId, checkType);
        if (po == null) {
            return null;
        }
        
        HealthCheckRecordEntity entity = new HealthCheckRecordEntity();
        BeanUtils.copyProperties(po, entity);
        return entity;
    }

    // ==================== 健康报告相关 ====================
    
    @Override
    public HealthReportEntity generateHealthReport(Long userId) {
        // 获取用户健康档案
        HealthProfileEntity profile = getHealthProfile(userId);
        if (profile == null) {
            throw new RuntimeException("用户健康档案不存在");
        }
        
        // 获取最近的健康检查记录
        List<HealthCheckRecordEntity> records = getHealthCheckRecords(userId, null);
        if (records.isEmpty()) {
            throw new RuntimeException("暂无健康检查记录");
        }
        
        // 计算健康评分
        Integer healthScore = calculateHealthScore(userId);
        
        // 评估风险等级
        String riskLevel = assessHealthRisk(userId);
        
        // 生成报告内容
        String reportContent = generateReportContent(profile, records, healthScore, riskLevel);
        
        // 生成健康建议
        String recommendations = generateRecommendations(profile, records, healthScore, riskLevel);
        
        // 创建报告实体
        HealthReportEntity report = new HealthReportEntity();
        report.setUserId(userId);
        report.setReportTitle("健康评估报告");
        report.setReportType("综合评估");
        report.setReportContent(reportContent);
        report.setHealthScore(healthScore);
        report.setRiskLevel(riskLevel);
        report.setRecommendations(recommendations);
        report.setGenerateTime(new Date());
        report.setStatus(1);
        report.setCreateTime(new Date());
        report.setUpdateTime(new Date());
        
        // 保存到数据库
        HealthReport po = new HealthReport();
        BeanUtils.copyProperties(report, po);
        healthReportDao.insert(po);
        report.setId(po.getId());
        
        return report;
    }

    @Override
    public List<HealthReportEntity> getHealthReports(Long userId) {
        List<HealthReport> pos = healthReportDao.selectByUserId(userId);
        return pos.stream().map(po -> {
            HealthReportEntity entity = new HealthReportEntity();
            BeanUtils.copyProperties(po, entity);
            return entity;
        }).collect(Collectors.toList());
    }

    @Override
    public HealthReportEntity getHealthReportById(Long reportId) {
        HealthReport po = healthReportDao.selectById(reportId);
        if (po == null) {
            return null;
        }
        
        HealthReportEntity entity = new HealthReportEntity();
        BeanUtils.copyProperties(po, entity);
        return entity;
    }

    // ==================== 健康预警相关 ====================
    
    @Override
    public void checkAndGenerateAlerts(Long userId) {
        // 获取最新的健康检查记录
        List<HealthCheckRecordEntity> records = getHealthCheckRecords(userId, null);
        if (records.isEmpty()) {
            return;
        }
        
        // 检查血压预警
        checkBloodPressureAlert(userId, records);
        
        // 检查心率预警
        checkHeartRateAlert(userId, records);
        
        // 检查血糖预警
        checkBloodSugarAlert(userId, records);
        
        // 检查BMI预警
        checkBMIAlert(userId, records);
    }

    @Override
    public List<HealthAlertEntity> getHealthAlerts(Long userId) {
        List<HealthAlert> pos = healthAlertDao.selectByUserId(userId);
        return pos.stream().map(po -> {
            HealthAlertEntity entity = new HealthAlertEntity();
            BeanUtils.copyProperties(po, entity);
            return entity;
        }).collect(Collectors.toList());
    }

    @Override
    public List<HealthAlertEntity> getUnreadAlerts(Long userId) {
        List<HealthAlert> pos = healthAlertDao.selectUnreadByUserId(userId);
        return pos.stream().map(po -> {
            HealthAlertEntity entity = new HealthAlertEntity();
            BeanUtils.copyProperties(po, entity);
            return entity;
        }).collect(Collectors.toList());
    }

    @Override
    public void markAlertAsRead(Long alertId) {
        healthAlertDao.markAsRead(alertId);
    }

    @Override
    public void markAlertAsHandled(Long alertId) {
        healthAlertDao.markAsHandled(alertId, new Date());
    }

    // ==================== 综合健康评估 ====================
    
    @Override
    public Integer calculateHealthScore(Long userId) {
        int score = 100; // 基础分数
        
        // 获取健康档案
        HealthProfileEntity profile = getHealthProfile(userId);
        if (profile != null) {
            // BMI评分
            BigDecimal bmi = profile.calculateBMI();
            if (bmi != null) {
                if (bmi.compareTo(new BigDecimal("18.5")) < 0 || bmi.compareTo(new BigDecimal("24")) > 0) {
                    score -= 10; // BMI异常扣10分
                }
            }
        }
        
        // 获取最近的健康检查记录
        List<HealthCheckRecordEntity> records = getHealthCheckRecords(userId, null);
        if (!records.isEmpty()) {
            HealthCheckRecordEntity latestRecord = records.get(0);
            
            // 血压评分
            if (!latestRecord.isBloodPressureNormal()) {
                score -= 15; // 血压异常扣15分
            }
            
            // 心率评分
            if (!latestRecord.isHeartRateNormal()) {
                score -= 10; // 心率异常扣10分
            }
            
            // 血糖评分
            if (!latestRecord.isBloodSugarNormal()) {
                score -= 15; // 血糖异常扣15分
            }
        }
        
        return Math.max(0, score); // 最低0分
    }

    @Override
    public String assessHealthRisk(Long userId) {
        Integer score = calculateHealthScore(userId);
        
        if (score >= 80) {
            return "低";
        } else if (score >= 60) {
            return "中";
        } else {
            return "高";
        }
    }

    // ==================== 私有方法 ====================
    
    /**
     * 检查血压预警
     */
    private void checkBloodPressureAlert(Long userId, List<HealthCheckRecordEntity> records) {
        HealthCheckRecordEntity latestRecord = records.get(0);
        if (latestRecord.getSystolicPressure() != null && latestRecord.getDiastolicPressure() != null) {
            String alertLevel = "低";
            String alertTitle = "";
            String alertContent = "";
            String suggestion = "";
            
            if (latestRecord.getSystolicPressure() > 180 || latestRecord.getDiastolicPressure() > 110) {
                alertLevel = "紧急";
                alertTitle = "血压严重异常预警";
                alertContent = "您的血压严重超出正常范围，请立即就医";
                suggestion = "立即前往医院就诊，可能需要药物治疗";
            } else if (latestRecord.getSystolicPressure() > 140 || latestRecord.getDiastolicPressure() > 90) {
                alertLevel = "高";
                alertTitle = "高血压预警";
                alertContent = "您的血压偏高，需要注意控制";
                suggestion = "建议减少盐分摄入，适当运动，定期监测血压";
            } else if (latestRecord.getSystolicPressure() < 90 || latestRecord.getDiastolicPressure() < 60) {
                alertLevel = "中";
                alertTitle = "低血压预警";
                alertContent = "您的血压偏低，需要注意";
                suggestion = "建议适当增加盐分摄入，避免突然起立";
            }
            
            if (!"低".equals(alertLevel)) {
                createAlert(userId, "血压", alertLevel, alertTitle, alertContent, 
                          "收缩压:" + latestRecord.getSystolicPressure() + ", 舒张压:" + latestRecord.getDiastolicPressure(),
                          "收缩压90-140mmHg, 舒张压60-90mmHg", suggestion);
            }
        }
    }
    
    /**
     * 检查心率预警
     */
    private void checkHeartRateAlert(Long userId, List<HealthCheckRecordEntity> records) {
        HealthCheckRecordEntity latestRecord = records.get(0);
        if (latestRecord.getHeartRate() != null) {
            String alertLevel = "低";
            String alertTitle = "";
            String alertContent = "";
            String suggestion = "";
            
            if (latestRecord.getHeartRate() > 120 || latestRecord.getHeartRate() < 50) {
                alertLevel = "高";
                alertTitle = "心率异常预警";
                alertContent = "您的心率异常，需要关注";
                suggestion = "建议就医检查，避免剧烈运动";
            } else if (latestRecord.getHeartRate() > 100 || latestRecord.getHeartRate() < 60) {
                alertLevel = "中";
                alertTitle = "心率偏高/偏低预警";
                alertContent = "您的心率偏高/偏低，需要注意";
                suggestion = "建议适当运动，保持良好作息";
            }
            
            if (!"低".equals(alertLevel)) {
                createAlert(userId, "心率", alertLevel, alertTitle, alertContent,
                          String.valueOf(latestRecord.getHeartRate()), "60-100次/分", suggestion);
            }
        }
    }
    
    /**
     * 检查血糖预警
     */
    private void checkBloodSugarAlert(Long userId, List<HealthCheckRecordEntity> records) {
        HealthCheckRecordEntity latestRecord = records.get(0);
        if (latestRecord.getBloodSugar() != null) {
            String alertLevel = "低";
            String alertTitle = "";
            String alertContent = "";
            String suggestion = "";
            
            if (latestRecord.getBloodSugar().compareTo(new BigDecimal("11.1")) > 0) {
                alertLevel = "高";
                alertTitle = "血糖异常预警";
                alertContent = "您的血糖严重偏高，需要立即就医";
                suggestion = "立即就医检查，可能需要药物治疗";
            } else if (latestRecord.getBloodSugar().compareTo(new BigDecimal("6.1")) > 0) {
                alertLevel = "中";
                alertTitle = "血糖偏高预警";
                alertContent = "您的血糖偏高，需要注意控制";
                suggestion = "建议控制饮食，适当运动，定期监测血糖";
            }
            
            if (!"低".equals(alertLevel)) {
                createAlert(userId, "血糖", alertLevel, alertTitle, alertContent,
                          latestRecord.getBloodSugar().toString(), "3.9-6.1 mmol/L", suggestion);
            }
        }
    }
    
    /**
     * 检查BMI预警
     */
    private void checkBMIAlert(Long userId, List<HealthCheckRecordEntity> records) {
        HealthCheckRecordEntity latestRecord = records.get(0);
        if (latestRecord.getBmi() != null) {
            String alertLevel = "低";
            String alertTitle = "";
            String alertContent = "";
            String suggestion = "";
            
            if (latestRecord.getBmi().compareTo(new BigDecimal("30")) > 0) {
                alertLevel = "高";
                alertTitle = "BMI异常预警";
                alertContent = "您的BMI严重超标，需要减重";
                suggestion = "建议控制饮食，增加运动量，必要时寻求专业帮助";
            } else if (latestRecord.getBmi().compareTo(new BigDecimal("24")) > 0) {
                alertLevel = "中";
                alertTitle = "BMI偏高预警";
                alertContent = "您的BMI偏高，需要注意控制体重";
                suggestion = "建议适当控制饮食，增加运动";
            }
            
            if (!"低".equals(alertLevel)) {
                createAlert(userId, "BMI", alertLevel, alertTitle, alertContent,
                          latestRecord.getBmi().toString(), "18.5-24", suggestion);
            }
        }
    }
    
    /**
     * 创建预警
     */
    private void createAlert(Long userId, String alertType, String alertLevel, String alertTitle, 
                           String alertContent, String currentValue, String normalRange, String suggestion) {
        HealthAlert po = new HealthAlert();
        po.setUserId(userId);
        po.setAlertType(alertType);
        po.setAlertLevel(alertLevel);
        po.setAlertTitle(alertTitle);
        po.setAlertContent(alertContent);
        po.setCurrentValue(currentValue);
        po.setNormalRange(normalRange);
        po.setSuggestion(suggestion);
        po.setIsRead(0);
        po.setIsHandled(0);
        po.setAlertTime(new Date());
        po.setCreateTime(new Date());
        po.setUpdateTime(new Date());
        
        healthAlertDao.insert(po);
    }
    
    /**
     * 生成报告内容
     */
    private String generateReportContent(HealthProfileEntity profile, List<HealthCheckRecordEntity> records, 
                                       Integer healthScore, String riskLevel) {
        StringBuilder content = new StringBuilder();
        content.append("健康评估报告\n\n");
        content.append("基本信息：\n");
        content.append("- 身高：").append(profile.getHeight()).append("cm\n");
        content.append("- 体重：").append(profile.getWeight()).append("kg\n");
        content.append("- BMI：").append(profile.calculateBMI()).append(" (").append(profile.getBMILevel()).append(")\n");
        content.append("- 血型：").append(profile.getBloodType()).append("\n\n");
        
        content.append("健康评分：").append(healthScore).append("分\n");
        content.append("风险等级：").append(riskLevel).append("\n\n");
        
        if (!records.isEmpty()) {
            HealthCheckRecordEntity latest = records.get(0);
            content.append("最新检查结果：\n");
            if (latest.getSystolicPressure() != null) {
                content.append("- 血压：").append(latest.getSystolicPressure()).append("/")
                       .append(latest.getDiastolicPressure()).append(" mmHg\n");
            }
            if (latest.getHeartRate() != null) {
                content.append("- 心率：").append(latest.getHeartRate()).append(" 次/分\n");
            }
            if (latest.getBloodSugar() != null) {
                content.append("- 血糖：").append(latest.getBloodSugar()).append(" mmol/L\n");
            }
        }
        
        return content.toString();
    }
    
    /**
     * 生成健康建议
     */
    private String generateRecommendations(HealthProfileEntity profile, List<HealthCheckRecordEntity> records, 
                                         Integer healthScore, String riskLevel) {
        StringBuilder recommendations = new StringBuilder();
        
        if (healthScore < 80) {
            recommendations.append("1. 建议定期进行健康检查\n");
        }
        
        if ("高".equals(riskLevel)) {
            recommendations.append("2. 建议及时就医进行专业诊断\n");
        }
        
        if (profile.calculateBMI() != null && profile.calculateBMI().compareTo(new BigDecimal("24")) > 0) {
            recommendations.append("3. 建议控制体重，适当运动\n");
        }
        
        if (!records.isEmpty()) {
            HealthCheckRecordEntity latest = records.get(0);
            if (!latest.isBloodPressureNormal()) {
                recommendations.append("4. 建议控制血压，减少盐分摄入\n");
            }
            if (!latest.isBloodSugarNormal()) {
                recommendations.append("5. 建议控制血糖，注意饮食\n");
            }
        }
        
        return recommendations.toString();
    }
}